﻿//#define TEST_EXCEPTION
//#define TEST_STATUS_CODE
//#define TEST_AUTHORIZATION

using System;
using System.IO;
using System.Net;
using HSS.Interlink.Web;
using Ionic.Zip;


namespace TestClient.Web
{
	public class DownloadHandler : HSS.Interlink.Web.BaseDownloadHandler
	{
		public DownloadHandler()
		{

		}

		public override HttpStatusCode GetSingleFile()
		{
			var result = HttpStatusCode.OK;

			#region Test Exceptions
#if TEST_EXCEPTION
			throw new Exception("Test Exception");
#endif
#if TEST_STATUS_CODE
			return HttpStatusCode.InternalServerError;
#endif
			#endregion

			#region Additional processing based on Query Command
			if (this.Query.Command == FileQueryCommand.OpenFileInline)
			{
				//// Enable client caching - default is false
				//this.EnableClientCache = true;
				//// Set the ClientCacheability - default is Public
				//this.ClientCacheability = System.Web.HttpCacheability.Public;
				//// Set the client cache expiration - default is 10 Minutes
				//this.ClientCacheExpiration = new TimeSpan(0, 10, 0);
			}
			#endregion

			// Your custom folder location for storing files.
			var myFileStore = Global.StoredFiles;
			var filePath = Path.Combine(this.GetFolder(myFileStore), this.RequestedFile);

			if (File.Exists(filePath))
				this.TransmitFile(filePath);
			else
				result = HttpStatusCode.NotFound;

			return result;
		}

		public override HttpStatusCode GetMultipleFiles()
		{
			#region Test Exceptions
#if TEST_EXCEPTION
			throw new Exception("Test Exception");
#endif
#if TEST_STATUS_CODE
			return HttpStatusCode.InternalServerError;
#endif
			#endregion

			var name = "tempFile";
			if (!string.IsNullOrEmpty(this.FileName))
				name = Path.GetFileNameWithoutExtension(this.FileName);
			if (string.IsNullOrEmpty(name))
				name = "tempFile";
			var archiveName = String.Format("{0}-{1}.zip", this.Query.JobId, name);

			// Could be whatever you wanted, but we use the existing DownloadTempCache
			// since the generated zip file will not be re-used and will automatically
			// be deleted from an AutoPurge cycle.
			var tempFile = DownloadTempCache.Current.Add(archiveName, (byte[])null);

			// Your custom folder location for storing files.
			var fileStore = this.GetFolder(Global.StoredFiles);

			var fileCount = 0;
			using (var zip = new ZipFile(archiveName))
			{
				zip.TempFileFolder = DownloadTempCache.Current.StoreDirectory;
				foreach (var file in this.RequestedFiles)
				{
					var fileName = Path.Combine(fileStore, file);
					if (File.Exists(fileName))
					{
						zip.AddFile(fileName, string.Empty);
						fileCount++;
					}
				}

				if (fileCount == 0)
					return HttpStatusCode.NotFound;

				zip.Save(tempFile);
			}

			this.TransmitFile(tempFile);

			return HttpStatusCode.OK;

		}

		public override HttpStatusCode OnError(Exception ex)
		{
			// Log the error
			
			// And specify your desired HTTP Response
			// http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
			return HttpStatusCode.InternalServerError;
		}

		public override bool IsAuthorized()
		{
			#region Test Exceptions
#if TEST_AUTHORIZATION
			return false;
#endif
			#endregion

			#region Validate Authorization
			//if (this.Context.User.Identity.IsAuthenticated)
			//{
			//    if (this.Context.User.IsInRole("requiredRole"))
			//        return true;
			//}
			//return false;
			#endregion

			return true;
		}

	}
}